package com.gitee.smalllog.core.utils;

import com.gitee.smalllog.core.model.Settings;
import com.gitee.smalllog.core.write.SafeWriter;

import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 继承Writer接口，用于json输出
 */
public class ElasticsearchOutputAggregator extends Writer {

	private Settings settings;
	private ErrorReporter errorReporter;
	private List<SafeWriter> writers;

	public ElasticsearchOutputAggregator(Settings settings, ErrorReporter errorReporter) {
		this.writers = new ArrayList<SafeWriter>();
		this.settings = settings;
		this.errorReporter = errorReporter;
	}

	public void addWriter(SafeWriter writer) {
		writers.add(writer);
	}

	/**
	 * 重写write方法
	 * @param cbuf
	 * @param off
	 * @param len
	 * @throws IOException
	 */
	@Override
	public void write(char[] cbuf, int off, int len) throws IOException {
		/**
		 * 循环writers，把结果集写入
		 */
		for (SafeWriter writer : writers) {
			writer.write(cbuf, off, len);
		}
	}

	public boolean hasPendingData() {
		for (SafeWriter writer : writers) {
			if (writer.hasPendingData()) {
				return true;
			}
		}
		return false;
	}

	public boolean hasOutputs() {
		return !writers.isEmpty();
	}

	public boolean sendData() {
		boolean success = true;
		for (SafeWriter writer : writers) {
			try {
				writer.sendData();
			} catch (IOException e) {
				success = false;
				errorReporter.logWarning("Failed to send events to Elasticsearch: " + e.getMessage());
//				if (settings.isHasErrorsToStderr()) {
//					System.err.println("[" + new Date().toString() + "] Failed to send events to Elasticsearch: " + e.getMessage());
//				}

			}
		}
		return success;
	}

	@Override
	public void flush() throws IOException {
		// No-op
	}

	@Override
	public void close() throws IOException {
		// No-op
	}

}
